package com.lanou3g.k12.service.impl;

import com.lanou3g.k12.entity.Course;
import com.lanou3g.k12.mapper.CourseMapper;
import com.lanou3g.k12.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    private CourseMapper courseMapper;

    //查找方法

    /**
     *
     * @param page 分页助手参数 页数
     * @param size 分页助手参数 数量
     * @return
     */
    @Override
    public  List<Course> findAllCourse(Integer page,Integer size) {
        List<Course> courseList = courseMapper.findAllCourse();
        return courseList;
    }

    /**
     *
     * @param page   分页助手参数 页数
     * @param keyword 关键字(模糊查询参数)
     * @param size 分页助手参数 数量
     * @return
     */
    @Override
    //模糊查询
    public  List<Course> search(Integer page,String keyword,Integer size) {
        List<Course> courseList = courseMapper.findByKeyword("%"+keyword+"%");
        return courseList;
    }


    @Override
    //批量删除
    public void deleteSomeCourse(Long[] ids) {
        courseMapper.deleteSomeCourse(ids);
    }
    //查找一个
    @Override
    public Course searchByID(Long id) {
        Course course = courseMapper.searchByID(id);
        return course;
    }
    //添加
    @Transactional
    @Override
    public void insertCourse(Course course) {
        Date date = new Date();
        course.setCreateTime(date);
        course.setUpdateTime(date);
        if (course.getSort()==null){
            course.setSort(1);
        }
        Integer sort = course.getSort();
        Course course1 = courseMapper.searchByID(course.getId());
        if(course1.getSort()!=null){
            courseMapper.updateAfterCourse(sort);
            courseMapper.insertCourse(course);
        }else {
            courseMapper.insertCourse(course);
        }
    }
    //修改
    @Transactional
    @Override
    public void updateCourse(Long id, Course course) {
        Date date = new Date();
        course.setUpdateTime(date);
        Course course1 = courseMapper.searchByID(id);
        if (course1.getSort()==null){
            course1.setSort(1);
        }
        Integer sort = course.getSort();
        if(course1.getSort()!=null&&course1.getSort()!=course.getSort()){
            courseMapper.updateAfterCourse(sort);
            courseMapper.updateCourse(course);
        }else {
            courseMapper.updateCourse(course);
        }
    }
    //删除单个
    @Override
    public void deleteOneCourse(Long id) {
        courseMapper.deleteOneCourse(id);
    }
    //插入修改
    @Override
    public void updateAfterCourse(Integer sort) {
        courseMapper.updateAfterCourse(sort);
    }

}
